package com.chinairi.mall.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.chinairi.common.utils.IdGenerator;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.dao.CompShopMapper;
import com.chinairi.mall.dao.ContractMatMapper;
import com.chinairi.mall.dao.GoodsInfoMapper;
import com.chinairi.mall.dao.MaterialMapper;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.service.modelobject.GoodsInfoMO;
import com.chinairi.mall.service.modelobject.MaterialMO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author gsl
 * @date 2020-11-05 21:42
 */
public class ExcelUploadDataListenerUtil extends AnalysisEventListener<GoodsInfoMO> {


    /**
     * 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUploadDataListenerUtil.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<GoodsInfoMO> list = new ArrayList<>();
    public GoodsInfoMapper goodsInfoMapper;
    public MaterialMapper materialMapper;
    public ContractMatMapper contractMatMapper;
    public CompShopMapper compShopMapper;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param goodsInfoMapper
     */
    public ExcelUploadDataListenerUtil(GoodsInfoMapper goodsInfoMapper) {
        this.goodsInfoMapper = goodsInfoMapper;
    }

    public ExcelUploadDataListenerUtil(GoodsInfoMapper goodsInfoMapper, MaterialMapper materialMapper, ContractMatMapper contractMatMapper, CompShopMapper compShopMapper) {
        this.goodsInfoMapper = goodsInfoMapper;
        this.materialMapper = materialMapper;
        this.contractMatMapper = contractMatMapper;
        this.compShopMapper = compShopMapper;

    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */


    @Override
    public void invoke(GoodsInfoMO data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }


    /**
     * 加上存储数据库
     */
    private void saveData() {
        Map<String, MaterialMO> materialMoMap = new HashMap<>(16);
        List<String> matCodeList = new ArrayList<>();
        for (GoodsInfoMO data : list) {
            matCodeList.add(data.getGoodsMatCode());
        }
        List<MaterialMO> materialMOList = goodsInfoMapper.selectMaterialByMatCodeList(matCodeList, UserSession.getUserId());
        if (materialMOList.size() < list.size()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "上传失败: 有 " + (list.size() - materialMOList.size()) + " 条物料不属于合同内，请检查后重新上传");
        }
        if (materialMOList.size() > 0) {
            for (MaterialMO materialMO : materialMOList) {
                materialMoMap.put(materialMO.getMatCode(), materialMO);
            }
        }else {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "上传的物料不在您的合同内，上传失败");
        }
        for (GoodsInfoMO data : list) {
            data.setGoodsDbid(IdGenerator.UUID());
            MaterialMO materialMO = materialMoMap.get(data.getGoodsMatCode());
            if (materialMO != null) {
                data.setCsDbid(materialMO.getCsDbid());
                data.setGoodsMatName(materialMO.getMatName());
                data.setGoodsContractId(materialMO.getContDbid());
                //可供采购量
                Float goodsCanBuy = materialMO.getCmMatQty().multiply(materialMO.getCmSetPercentage().multiply(BigDecimal.valueOf(0.01))).floatValue();
                data.setGoodsCanBuy(goodsCanBuy);
                //合同价
                data.setGoodsContractPrice(materialMO.getCmSetPrice().floatValue());
                data.setGoodsStock(goodsCanBuy);
                data.setGoodsMatCode(materialMO.getMatDbid());
                data.setGoodsSpecifications(materialMO.getMatSpecifications());
                data.setGoodsSpecificationLevel(materialMO.getMatSpecificationLevel());
                data.setGoodsMeasuerUnit(materialMO.getMatMeasuerUnit());
                data.setGoodsAssistMeasure(materialMO.getMatAssistMeasure());
                data.setGoodsProduceCycle(materialMO.getMatProduceCycle());
                data.setGoodsMatTexture(materialMO.getMatTexture());
                data.setGoodsImplementStandard(materialMO.getMatImplementStandard());
                data.setGoodsGoodsWeight(materialMO.getMatWeight());
                data.setCsDbid(materialMO.getCsDbid());
            }
            data.setGoodsCreateTime(new Date());
            data.setGoodsCreateUser(UserSession.getUserId());
            data.setGoodsShelfState(0);
            data.setGoodsSetVisible(1);
            data.setGoodsApproveStatus(0);
        }
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        goodsInfoMapper.batchInsert(list);
        LOGGER.info("存储数据库成功！");
    }
}
